package io.geekidea.boot.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.geekidea.boot.business.entity.Hazard;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.framework.page.OrderByItem;
import io.geekidea.boot.framework.page.OrderMapping;
import io.geekidea.boot.framework.page.Paging;
import io.geekidea.boot.business.dto.HazardDto;
import io.geekidea.boot.business.mapper.HazardMapper;
import io.geekidea.boot.business.query.HazardQuery;
import io.geekidea.boot.business.service.HazardService;
import io.geekidea.boot.business.vo.HazardVo;
import io.geekidea.boot.util.PagingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * 设备列 服务实现类
 *
 * @author mr.wei
 * @since 2024-04-10
 */
@Slf4j
@Service
public class HazardServiceImpl extends ServiceImpl<HazardMapper, Hazard> implements HazardService {

    @Autowired
    private HazardMapper hazardMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addHazard(HazardDto dto) {
        Hazard hazard = new Hazard();
        BeanUtils.copyProperties(dto, hazard);

        if (hazard.getId() != null) {
            throw new BusinessException("设备列已存在");
        }
        return save(hazard);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateHazard(HazardDto dto) {
        Long id = dto.getId();
        Hazard hazard = getById(id);
        if (hazard == null) {
            throw new BusinessException("设备列不存在");
        }
        BeanUtils.copyProperties(dto, hazard);
        return updateById(hazard);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteHazard(Long id) {
        return removeById(id);
    }

    @Override
    public HazardVo getHazardById(Long id) {
        return hazardMapper.getHazardById(id);
    }

    @Override
    public Paging<HazardVo> getHazardPage(HazardQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        orderMapping.put("createTime", "create_time");
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<HazardVo> list = hazardMapper.getHazardPage(query);
        Paging<HazardVo> paging = new Paging<>(list);
        return paging;
    }

    @Override
    public List<HazardVo> getHazardList(HazardQuery query) {
        List<HazardVo> list = hazardMapper.getHazardList(query);
        return list;
    }

}
